package org.example.gen;

import org.example.entity.TotalVillageInfo;
import org.example.http.HttpUtil;
import org.example.http.ParamEntity;
import org.example.tool.ExcelTool;
import org.example.LandEntity;
import org.example.LogInterface;
import org.example.area.AreaDto;
import org.example.area.AreaList;
import org.example.excel.ExcelRow;
import org.example.word.DocxStamperUtil;
import org.example.word.ReportData;
import org.example.word.TableRow;

import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.example.word.DocxReplaceUtil.insertData;

public class WordGen implements CallBack {
    private final LogInterface log;
    private List<ExcelRow> excelRows;
    private String ybbl;
    private final Map<String, List<LandEntity>> tempLands;
    private final Map<String,List<Map<String, Object>>> inspectionReportList;
    private Map<String, TotalVillageInfo> totalVillageInfoMap;
    public WordGen(LogInterface log, String excelPath, String bigDecimal, Map<String, List<LandEntity>> tempLands, Map<String,List<Map<String, Object>>> inspectionReportList, Map<String, TotalVillageInfo> totalVillageInfoMap) {
        this.log = log;
        this.ybbl = bigDecimal;
        this.tempLands = tempLands;
        this.inspectionReportList = inspectionReportList;
        this.totalVillageInfoMap=totalVillageInfoMap;
        //读取excel数据
        try {
            excelRows = ExcelTool.readExcel(excelPath);
        } catch (Exception e) {
            log.logError("excel数据读取失败");
            e.printStackTrace();
        }
    }
    @Override
    public boolean doWork(String nf, String bxgsmc, String qhdm, String zwmc, String dirPath) {
        log.logInfo(String.format("开始生成%s-%s-%s-%s的遥感验标报告", nf,bxgsmc,qhdm,zwmc));
        List<Map<String, Object>> inspectionReportList = this.inspectionReportList.get(qhdm+zwmc);
        if(inspectionReportList == null){
            log.logError("未找到匹配"+qhdm+zwmc+"的验标数据");
            return true;
        }
        List<LandEntity> lands = tempLands.get(qhdm+zwmc);
        if(lands.isEmpty()){
            log.logError(String.format("没有找到%s-%s的记录，无法生成专题图", qhdm, zwmc));
        }
        // 获取模板文件
        ClassLoader classLoader = getClass().getClassLoader();
        InputStream templateStream = classLoader.getResourceAsStream("templates/report.docx");
        // 匹配excel数据
        ExcelRow excelRow = excelRows.stream()
                .filter(row -> row.getZwmc().equals(zwmc))
                .findFirst()
                .orElse(null);

        if(excelRow == null) {
            log.logError("未找到匹配"+zwmc+"的excel数据");
            return true;
        }
        // 生成目标文件路径
        AreaDto area = AreaList.getFullNameEntity(qhdm);
        TotalVillageInfo totalVillageInfo = totalVillageInfoMap.get(qhdm+zwmc);
        // 准备数据模型
        ReportData data = new ReportData();
        data.setNf(nf);
        data.setBxgsmc(bxgsmc);
        data.setZwmc(zwmc);
        data.setZwmc1(zwmc);
        data.setDate1(convertLocalDateToString(excelRow.getYbsj()));
        data.setDate2(convertLocalDateToString(excelRow.getYgyxsj()));
        data.setDate3(convertLocalDateToString(excelRow.getBgsj()));
        data.setPercent(ybbl);
        data.setBxgsjc(excelRow.getBxgsjc());
        data.setProvince(area.getProvinceName());
        data.setProvince1(area.getProvinceName());
        data.setCity(area.getCityName());
        data.setCounty(area.getCountyName());
        data.setTown(area.getTownName());
        data.setVillage(area.getVillageName());
        data.setZtbhs(totalVillageInfo.getTotalPerson());
        //从inspectionReportList中，取map中tbmj的和

        BigDecimal tbmj = totalVillageInfo.getTotalMj();
        //tbmj保留2位小数
        tbmj = tbmj.setScale(2, RoundingMode.HALF_UP);
        data.setZtbmj(tbmj);

        List<TableRow> tableRows = new ArrayList<>();
        for (int i = 0; i < inspectionReportList.size(); i++) {
            Map<String, Object> map = inspectionReportList.get(i);
            TableRow tableRow = new TableRow();
            tableRow.setQhmc(area.getVillageName());
            tableRow.setNhxm(map.get("nhxm").toString());
            tableRow.setNhdm(map.get("nhdm").toString());
            tableRow.setZwmc(zwmc);
            tableRow.setTbmj( new BigDecimal(map.get("tbmj").toString()));
            tableRows.add(tableRow);
        }

        String targetFileName = nf + area.getCountyName() + area.getTownName() +
                area.getVillageName() + zwmc + "temp.docx";
        String targetFileName1 = nf + area.getCountyName() + area.getTownName() +
                area.getVillageName() + zwmc + "遥感验标报告.docx";
        String targetPath = dirPath + File.separator + targetFileName;
        System.out.println(dirPath);
        System.out.println(dirPath + File.separator + targetFileName1);
        System.out.println(targetPath);
        ParamEntity paramEntity = ParamEntity.fromLandEntity(lands, zwmc, excelRow.getRasterId());
        try {
            log.logInfo("开始生成文档: " + targetPath);
            String base64= HttpUtil.httpPostQueryMap(paramEntity);

            // 使用 docx-stamper 生成文档
            DocxStamperUtil.generateDocument(templateStream, data, targetPath);
            log.logInfo("报告生成成功: " + targetPath);
            insertData(targetPath, dirPath + File.separator + targetFileName1,tableRows,base64);
            //删除临时文件
            new File(targetPath).delete();
            return true;
        } catch (Exception e) {
            log.logError("生成文档失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }


    private static String convertLocalDateToString(LocalDate date) {
        if (date == null) {
            return "";
        }
        return date.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
    }

}
